package com.eelye.util.winui.manager;

import com.eelye.util.winui.window.Window;
import com.eelye.util.winui.window.WindowFactory;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef.HWND;
import org.springframework.stereotype.Service;

import static com.eelye.util.winui.constant.Const.WAIT_INTERVAL;

@Service
public class WindowManager {

    public static Window getCurrentWindow() {
        return new Window(User32.INSTANCE.GetForegroundWindow());
    }
    public static Window findTopWindow(String className, boolean clsEqual, String text, boolean textEqual, int timeout) {
        int elapsed = timeout;

        while (elapsed > 0) {
            elapsed -= 5;

            Window window = findTopWindow(className, clsEqual, text, textEqual);
            if (null != window) {
                return window;
            }

            try {
                Thread.sleep(WAIT_INTERVAL);
            } catch (InterruptedException e) {
                break;
            }
        }

        return null;
    }

    public static Window findTopWindow(String className, boolean clsEqual, String text, boolean textEqual) {
        User32 user32 = User32.INSTANCE;
        HWND[] result = new HWND[1];
        user32.EnumWindows((hWnd, arg) -> {
            boolean clsFound = false;
            boolean txtFound = false;
            String clsName = Window.getClassName(hWnd);

            if (clsEqual) {
                clsFound = clsName.equals(className);
            } else {
                clsFound = clsName.contains(className);
            }

            if (!clsFound) {
                return true;
            }

            String txt = Window.getText(hWnd);
            if (textEqual) {
                txtFound = txt.equals(text);
            } else {
                txtFound = txt.contains(text);
            }

            if (txtFound) {
                result[0] = hWnd;

                return false;
            }

            return true;
        }, null);

        if (null == result[0]) {
            return null;
        }

        return WindowFactory.buildWindow(result[0], className);
    }
}
